﻿using System;
using System.Configuration;
using System.IO;
using System.Text.RegularExpressions;
using System.Web;
using System.Reflection;

namespace NExt.Handler.Base.Default
{
    public class EmbeddedResourceResponseStreamBuilder : IReponseStreamBuilder
    {
        private const string ROOT_PATH = "/";
        private readonly Assembly assembly;
        private readonly string virtualPath;

        public EmbeddedResourceResponseStreamBuilder(Assembly assembly)
        {
            this.assembly = assembly;
            this.virtualPath = HttpRuntime.AppDomainAppVirtualPath;
        }

        public Stream Build(HttpContext context)
        {
            Uri uri = context.Request.Url;
            string resourceName = GetResourceName(assembly, uri);
            Stream stream = assembly.GetManifestResourceStream(resourceName);
            return stream;
        }

        private string GetResourceName(Assembly assembly, Uri uri)
        {
            string resourceUri = GetResourceUri(uri);
            string resourceName = resourceUri.Replace("/", ".");
            string resourceFullName = string.Format("{0}{1}", assembly.GetName().Name, resourceName);
            return resourceFullName;
        }

        private string GetResourceUri(Uri uri)
        {
            if(virtualPath == ROOT_PATH)
            {
                return uri.AbsolutePath;
            }

            string resourceUri = Regex.Replace(uri.AbsolutePath, virtualPath, string.Empty, RegexOptions.IgnoreCase);
            return resourceUri;
        }
    }
}
